package com.open.capacity.user.controller;

import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysEmployee;
import com.open.capacity.user.service.SysEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 員工
 */
@Slf4j
@RestController
@Api(tags = "員工模块api")
public class SysEmployeeController {

    @Autowired
    private SysEmployeeService employeeService;


    @GetMapping("/employees/{id}")
    public SysEmployee findUserById(@PathVariable(value = "id") String id) {
        return employeeService.findById(id);
    }

    @GetMapping("/employees/getName")
    public Result getName(@RequestParam(value = "keyValue") String keyValue) {
        SysEmployee user = employeeService.findById(keyValue);
        return Result.succeed(user == null ? "" : user.getRealName(), "获取成功！");
    }

    @GetMapping("/employees/getNames")
    public Result getNames(@RequestParam(value = "keyValue") String keyValue) {
        String[] idArray = keyValue.split(",");
        String nameStr = "";
        for (String userId : idArray) {
            SysEmployee employee = employeeService.findById(userId);
            if (employee != null) {
                if (StringUtils.isEmpty(nameStr)) {
                    nameStr += (employee.getRealName());
                } else {
                    nameStr += (", " + employee.getRealName());
                }
            }
        }
        return Result.succeed(nameStr,"success");
    }


    @GetMapping("/employees/findUserByIds")
    public Result<List<SysEmployee>> findUserByIds(@RequestParam String keyValue) {
        String[] idArray = keyValue.split(",");
        List<SysEmployee> userList = new ArrayList<>();
        for (String userId : idArray) {
            userList.add(employeeService.findById(userId));
        }
        return Result.succeed(userList);
    }


    /**
     * 修改 員工
     *
     * @param employee
     */
    @PutMapping("/employees")
    @LogAnnotation(module = " 員工", name = "更新")
    public void updateEmployee(@RequestBody SysEmployee employee) {
        employeeService.updateEmployee(employee);
    }


    /**
     *  員工查询
     *
     * @param params
     * @return
     */
    @ApiOperation(value = " 員工分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/employees")
    public PageResult<SysEmployee> pageAll(@RequestParam Map<String, Object> params) {
        return employeeService.pageAll(params);
    }

    /**
     *  員工查询
     *
     * @param companyId
     * @param departmentId
     * @param keyword
     * @return
     */
    @ApiOperation(value = " 員工查询列表")
    @GetMapping("/employees/list")
    public Result<List<SysEmployee>> list(@RequestParam(value = "companyId", required = false) String companyId, @RequestParam(value = "departmentId", required = false) String departmentId, @RequestParam(value = "keyword", required = false) String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("companyId", companyId);
        params.put("departmentId", departmentId);
        params.put("keyword", keyword);
        List<SysEmployee> list = employeeService.findAll(params);
        return Result.succeed(list);
    }


    @ApiOperation(value = "判断人员name是否存在")
    @GetMapping("/employees/existsName")
    public Result existsName(@RequestParam(value = "userName") String userName) {
        SysEmployee employee = employeeService.findByUsername(userName);
        return Result.succeed(employee != null);
    }



    /**
     * 更新 員工状态
     *
     * @param id
     * @author gitgeek
     */
    @PostMapping(value = "/employees/{id}/updateStatus")
    @LogAnnotation(module = " 員工", name = "更新状态")
    public Result updateStatus(@PathVariable(value = "id") String id, Integer status) {
        if (id.equals("1")) {
            return Result.failed("超级管理员不允许禁用");
        }
        employeeService.updateStatus(id, status);
        return Result.succeed(null, "更新成功");
    }



    /**
     * 新增or更新
     *
     * @param employee
     * @return
     */
    @PostMapping("/employees/saveOrUpdate")
    @PreAuthorize("hasAnyAuthority('user:post/users/saveOrUpdate')")
    @LogAnnotation(module = " 員工", name = "更新")
    public Result saveOrUpdate(@RequestBody SysEmployee employee, String keyValue) {
        return employeeService.saveOrUpdate(employee, keyValue);
    }

    /**
     * 删除人员
     * delete /users/1
     *
     * @param id
     */
    @ApiOperation(value = "删除人员")
    @DeleteMapping("/employees/{id}")
    @LogAnnotation(module = " 員工", name = "删除")
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            employeeService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {

            return Result.failed("操作失败");
        }
    }

    /**
     * 导入excel
     */
    @PostMapping("/employees/importExcel")
    @LogAnnotation(module = " 員工", name = "导入excel")
    public Result importExcel(String companyId, @RequestParam("file") MultipartFile multipartFile) throws Exception {
        int count = employeeService.importExcel(multipartFile, companyId);
        return Result.succeed(count, "导入成功");
    }

//    /**
//     * 导出数据
//     *
//     * @return
//     */
//    @GetMapping("/users/exportUser")
//    @PreAuthorize("hasAuthority('user:post/users/exportUser')")
//    public void exportUser(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
//        List<SysUserExcel> result = employeeService.findAll(params);
//
//        if (!CollectionUtils.isEmpty(result)) {
//            result.forEach(item -> {
//                if (item.getSex() != null && item.getSex().equals(1)) {
//                    item.setSexStr("男");
//                } else if (item.getSex() != null && item.getSex().equals(0)) {
//                    item.setSexStr("女");
//                }
//            });
//        }
//        response.setContentType("application/vnd.ms-excel");
//        response.setHeader("Content-disposition", "attachment;filename=users.xls");
//        OutputStream ouputStream = null;
//        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(" 員工导出", " 員工"),
//                SysUserExcel.class, result);
//        try {
//            ouputStream = response.getOutputStream();
//            workbook.write(ouputStream);
//        } catch (Exception e) {
//            throw new RuntimeException("系统异常");
//        } finally {
//            try {
//                if (ouputStream != null) {
//                    ouputStream.flush();
//                    ouputStream.close();
//                }
//            } catch (Exception e) {
//                throw new RuntimeException("系统异常");
//            }
//        }
//    }


}
